package com.hjj.filter;

import com.hjj.beans.User;
import com.hjj.services.UserServices;
import org.apache.ibatis.javassist.ClassPath;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {

        String requestURI = req.getRequestURI();

        System.out.println("正在过滤【" + requestURI + "】页面");

        // 在没用spring的情况下使用HttpServletRequest对象获取HttpSession对象
        HttpSession session = req.getSession();

        // 获取登录用户数据
        User user = (User)session.getAttribute("user");

        // 判断是否登录
        if (user == null){
            // 获取cookies中的所有数据
            Cookie[] cookies = req.getCookies();

            // 对cookies进行判空处理,防止后面出现空指针异常
            if (cookies == null){
                // 回到登录页面
                res.sendRedirect("/static/login.html");
                return;
            }

            String loginAct = "";
            String loginPwd = "";

            // 获取cookies中的用户信息
            for (Cookie cookie : cookies) {
                if ("loginAct".equals(cookie.getName())){
                    loginAct = cookie.getValue();
                }else if ("loginPwd".equals(cookie.getName())){
                    loginPwd = cookie.getValue();
                }
            }

            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            UserServices userServices = context.getBean("userServicesFilter", UserServices.class);

            // 查看是否有该用户
            User temp = userServices.getByUser(loginAct, loginPwd);

            if (temp == null) {
                // 回到登录页面
                res.sendRedirect("/static/login.html");
                return;
            }

            // 如果有就将该用户传入session对象中
            session.setAttribute("user", temp);
        }
        // 放行
        chain.doFilter(req, res);
    }
}
